package org.web.ssm.service.wechatService.wechatServiceImpl;

import org.web.ssm.model.wechatModel.CheckModel;
import org.web.ssm.utils.CheckUtils;
import org.springframework.stereotype.Service;
import org.web.ssm.service.wechatService.ICheckoutService;

import java.util.Arrays;

/**
 * Created by LUOLIANG on 2016/6/2.
 * 1）将token、timestamp、nonce三个参数进行字典序排序
 * 2）将三个参数字符串拼接成一个字符串进行sha1加密
 * 3）开发者获得加密后的字符串可与signature对比，标识该请求来源于微信
 */
@Service("checkoutService")
public class CheckoutServiceImpl implements ICheckoutService {
    //用户微信公众平台填写的token，可自定义
    private static final String token = "CounterDrops";

    /**
     * signature 微信加密签名，signature结合了开发者填写的token参数和请求中的timestamp参数、nonce参数。
     * timestamp 时间戳
     * nonce     随机数
     * echostr   随机字符串
     * boolean
     */
    public String checkSignature(CheckModel checkModel) {
        String signature = checkModel.getSignature();
        String timestamp = checkModel.getTimestamp();
        String nonce = checkModel.getNonce();
        String echostr = checkModel.getEchostr();
        String[] str = new String[]{token, timestamp, nonce};

        //字典排序
        Arrays.sort(str);

        //拼接三个字符串
        StringBuffer stringBuffer = new StringBuffer();
        for (String s : str) {
            stringBuffer.append(s);
        }

        //进行sha1加密
        String temp = CheckUtils.getSha1(stringBuffer.toString());

        if (temp.equals(signature))
            return echostr;
        else
            return "error";
    }
}
